package com.atguigu.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class zkClient {
    private String connection="192.168.80.130:2181,192.168.80.131:2181,192.168.80.132:2181";
    private Integer session=2000;
    private ZooKeeper zkClient;
    List<String> children;
    @Before
    public void init(){

        try {
            zkClient= new ZooKeeper(connection, session, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    System.out.println("*******************************************************************");
                    try {
                        children = zkClient.getChildren("/", true);
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    children.forEach(System.out::println);
                }
            });

        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    @Test
    public void CreateNode() throws InterruptedException, KeeperException {
        String s = zkClient.create("/atguigu", "java".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }
    @Test
    public void getChildren() throws InterruptedException, KeeperException {
        List<String> children = zkClient.getChildren("/", true);
        children.forEach(System.out::println);
        Thread.sleep(1000000);
    }
    @Test
    public void exist() throws InterruptedException, KeeperException {
        Stat exists = zkClient.exists("/atguigu", false);
        if (exists!=null){
            System.out.println("有");
        }else {
            System.out.println("没有");
        }
    }
}
